package com.comleader.uap.common.convert;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.comleader.uap.common.annotation.ExcelDictFormat;
import com.comleader.uap.pojo.dto.DictDataDTO;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;

/**
 * @Dscription 字典格式化转换处理
 * @Author 连新景
 * @Date 2024/12/11 17:50
 */
public class ExcelDictConvert implements Converter<Object> {

    /**
     * key为字典编码，value为字典数据列表
     */
    public static Map<String, List<DictDataDTO>> dictMap;

    @Override
    public Class<Object> supportJavaTypeKey() {
        return Object.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return null;
    }

    @Override
    public Object convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        return Converter.super.convertToJavaData(cellData, contentProperty, globalConfiguration);
    }

    @Override
    public WriteCellData<?> convertToExcelData(Object value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        if (ObjectUtil.isNull(value)) {
            return new WriteCellData<>("");
        }
        ExcelDictFormat annotation = getAnnotation(contentProperty.getField());
        String dictCode = annotation.dictCode();
        List<DictDataDTO> dictDataList = dictMap.getOrDefault(dictCode, new ArrayList<>());
        Map<String, String> map = CollStreamUtil.toMap(dictDataList, DictDataDTO::getValue, DictDataDTO::getName);
        String dictName = map.getOrDefault(Convert.toStr(value), "");
        return new WriteCellData<>(dictName);
    }

    private ExcelDictFormat getAnnotation(Field field) {
        return AnnotationUtil.getAnnotation(field, ExcelDictFormat.class);
    }

}
